# -*- encoding=utf8 -*-
"""
RedFlag-TC000030    美化参数统一
检查美化各参数默认值
"""
__author__ = "ldm"

import sys
import os
import yaml

# 获取当前脚本所在目录.py
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取上级目录.air
parent_dir = os.path.dirname(current_dir)
# 获取上级目录air
grandparent_dir = os.path.dirname(parent_dir)
# 获取和air目录平级的conf、testcase目录路径
conf_dir = os.path.join(grandparent_dir, 'conf')
testcase_dir = os.path.join(grandparent_dir, 'testcase')
# 将conf、testcase目录添加到sys.path
sys.path.append(conf_dir)
sys.path.append(testcase_dir)

from PageFunction import CameraVideoShooter
from elements import *

auto_setup(__file__)

shooter = CameraVideoShooter()

# 记录已经点击过的分类
clicked_categories = set()

log("-----------------------------封装点击美化操作-------------------------------------")

from poco.exceptions import PocoNoSuchNodeException

def apply_beauty(category, sub_category, beauty_name, should_slide=False, yaml_data=None):
    global clicked_categories
    category_element = poco(text=category)
    log(f"当前处理的一级分类: {category}")

    # 只有在该一级分类未被点击过时才点击一级分类
    if category not in clicked_categories:
        try:
            if category_element.exists():
                shooter.click_element(category_element)
                clicked_categories.add(category)
            else:
                log(f"{category_element} 元素不存在，执行滑动操作")
                shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))
        except PocoNoSuchNodeException as e:
            log(f"未找到 {category_element} 元素，错误信息: {e}，执行滑动操作")
            shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))
        except Exception as e:
            log(f"点击 {category_element} 元素时出现其他异常，错误信息: {e}，执行下滑操作")
            shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))

    sub_category_element = poco(text=sub_category)
    log(f"当前处理的二级分类: {sub_category}")

    element_found = False
    while not element_found:
        try:
            if sub_category_element.exists():
                shooter.click_element(sub_category_element)
                element_found = True
            else:
                log(f"{sub_category_element} 元素不存在，执行滑动操作")
                shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))
        except PocoNoSuchNodeException as e:
            log(f"未找到 {sub_category_element} 元素，错误信息: {e}，执行滑动操作")
            shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))
        except Exception as e:
            log(f"点击 {sub_category_element} 元素时出现其他异常，错误信息: {e}，执行下滑操作")
            shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))

    beauty_element = poco(text=beauty_name)
    log(f"当前处理的元素: {beauty_name}")

    element_found = False
    while not element_found:
        try:
            if beauty_element.exists():
                log(f"尝试点击元素: {beauty_element.get_text()}，预期元素: {beauty_name}")
                shooter.click_element(beauty_element)
                element_found = True
            else:
                log(f"{beauty_element} 元素不存在，执行滑动操作")
                shooter.swipe_screen((0.80, 0.88), (0.1, 0.88))
        except PocoNoSuchNodeException as e:
            log(f"未找到 {beauty_element} 元素，错误信息: {e}，执行滑动操作")
            shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))
        except Exception as e:
            log(f"点击元素 {beauty_element} 时出现其他异常，错误信息: {e}，执行下滑操作")
            shooter.swipe_screen((0.85, 0.88), (0.1, 0.88))

    beauty_text = ""
    try:
        element = poco("cn.migu.video.clip.walle:id/currentprogress")
        beauty_text = shooter.get_element_text(element)
    except PocoNoSuchNodeException:
        log(f"获取节点的文本信息时，未找到元素 cn.migu.video.clip.walle:id/currentprogress")
        beauty_text = None  # 将 beauty_text 设置为 None，明确其状态

    # 当点击“无”时，增加判断逻辑
    if beauty_name == "无":
        try:
            shooter.assert_element_not_exists(poco("cn.migu.video.clip.walle:id/currentprogress"),"断言失败，选择无后还是能获取到腮红的参数")
            # 查找并点击 return 对应的元素
            found_return_element = False
            for category_info in yaml_data['beauty_elements']:
                if category_info['category'] == category:
                    for sub_node in category_info['nodes']:
                        if sub_node.get('category') == sub_category:
                            for node in sub_node['nodes']:
                                if isinstance(node, dict) and 'text' in node and node['text'] == beauty_name and'return' in node:
                                    return_element = poco(node['return'])
                                    log(f"尝试定位 {beauty_name} 的 return 元素，定位路径: {node['return']}")
                                    if return_element.exists():
                                        log(f"{beauty_name} 的 return 元素已定位成功")
                                        found_return_element = True
                                        try:
                                            shooter.click_element(return_element)
                                            log(f"已点击 {beauty_name} 的 return 元素返回上级页面")
                                        except Exception as click_err:
                                            log(f"点击 {beauty_name} 的 return 元素时出错: {click_err}")
                                    else:
                                        log(f"{beauty_name} 的 return 元素未定位到，定位路径: {node['return']}")
            if not found_return_element:
                log(f"未找到 {beauty_name} 的 return 元素")
            # 当点击“无”时，不进行预期值断言
            return
        except PocoNoSuchNodeException:
            log(f"断言成功，未找到元素 cn.migu.video.clip.walle:id/currentprogress")
            # 当点击“无”时，不进行预期值断言
            return
    else:
        # 从YAML数据中获取预期值
        expected_value = None
        if yaml_data:
            for category_info in yaml_data['beauty_elements']:
                if category_info['category'] == category:
                    for sub_node in category_info['nodes']:
                        if sub_node.get('category') == sub_category:
                            for node in sub_node['nodes']:
                                if isinstance(node, dict) and 'text' in node and node['text'] == beauty_name:
                                    expected_value = node.get('expected_value')
                                    break
                            if expected_value is not None:
                                break
                    if expected_value is not None:
                        break

    if expected_value is not None and beauty_text is not None:
        shooter.assert_texts_equal(beauty_text, str(expected_value),
                                   f"断言失败，预期参数 {expected_value} 与实际展示参数 {beauty_text} 不符合")
        log(f"{beauty_name} 美化应用成功")
    else:
        log(f"未找到 {beauty_name} 的预期值 或 未获取到实际展示参数，无法进行断言")

log("-----------------------------应用所有美化效果-------------------------------------")
"""
进入相机拍摄
点击美化
拼接yaml文件路径
判断是否找到yaml文件中的数据，如果找到则加载内容到data变量，如果没有找到记录错误并抛出异常
定义列表中包含需要滑动的美化名称
遍历yaml文件中的美化分类信息，从分类信息提取分类系节点
从美化中提取到节点名称
"""
shooter.enter_photograph()
shooter.click_element(shooting_page_beautify)

# 读取 YAML 文件
yaml_file_path = os.path.join(grandparent_dir, 'conf', 'TC000031_beautify_element_positioning.yaml' )
try:
    with open(yaml_file_path, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
except FileNotFoundError:
    log(f"错误：未找到文件 {yaml_file_path}，请检查文件路径是否正确。")
    stop_app(UGC_package_name)
    raise

# 需要滑动操作的美化列表，你可以根据实际情况调整
slidable_beauties = []

# 遍历从YAML文件中加载的美化分类信息
for category_info in data['beauty_elements']:
    category = category_info['category']
    for sub_node in category_info['nodes']:
        if isinstance(sub_node, dict) and 'category' in sub_node:
            sub_category = sub_node['category']
            for node in sub_node['nodes']:
                if isinstance(node, dict) and 'text' in node:
                    beauty_name = node['text']
                    log(f"当前处理一级分类: {category}，二级分类: {sub_category}，节点: {beauty_name}")
                    should_slide = beauty_name in slidable_beauties
                    apply_beauty(category, sub_category, beauty_name, should_slide, yaml_data=data)
# 关闭APP
stop_app("cn.migu.video.clip.walle")